package com.news.servlet.admin;

import com.news.model.News;
import com.news.model.Sort;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/newsManage")
public class NewsManageServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();
    private static final int PAGE_SIZE = 10;  // 每页显示的新闻数量

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取当前页码
            int currentPage = 1;
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }

            // 获取搜索关键词
            String keyword = request.getParameter("keyword");

            // 获取新闻总数和总页数
            int totalNews = newsService.getNewsCount(keyword);
            int totalPages = (totalNews + PAGE_SIZE - 1) / PAGE_SIZE;

            // 获取当前页的新闻列表
            List<News> newsList = newsService.getNewsByPage(currentPage, PAGE_SIZE, keyword);
            
            // 获取分类列表（用于显示分类名称）
            List<Sort> sortList = newsService.getAllSorts();

            // 设置属性
            request.setAttribute("newsList", newsList);
            request.setAttribute("sortList", sortList);
            request.setAttribute("currentPage", currentPage);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("keyword", keyword);

            // 转发到新闻管理页面
            request.getRequestDispatcher("/admin/news_manage.jsp").forward(request, response);
        } catch (Exception e) {
            request.getSession().setAttribute("message", "获取新闻列表失败：" + e.getMessage());
            request.getRequestDispatcher("/admin/news_manage.jsp").forward(request, response);
        }
    }
} 